package com.cjkj.applet.controller;

import com.cjkj.applet.domain.dto.PatientRequest;
import com.cjkj.applet.service.ITPatIndexService;
import com.cjkj.applet.service.ITPatVisitService;
import com.cjkj.common.core.constant.EquipmentConstants;
import com.cjkj.common.core.constant.RegConstants;
import com.cjkj.common.core.utils.DateUtils;
import com.cjkj.common.core.utils.IDCardValidator;
import com.cjkj.common.core.web.domain.AjaxResult;
import com.cjkj.common.log.annotation.Log;
import com.cjkj.common.log.enums.BusinessType;
import com.cjkj.common.security.annotation.RepeatSubmit;
import com.cjkj.common.security.service.AppletTokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.util.Date;
import java.util.List;

/**
 * 患者信息控制器
 */
@RestController
@RequestMapping("/patient")
@Validated
public class PatientController {

    @Resource
    private ITPatVisitService visitService;

    @Resource
    private ITPatIndexService patIndexService;

    @Resource
    private AppletTokenService appletTokenService;

    /**
     * 开单
     * @param params
     * @return
     */
    @PostMapping("data")
    @RepeatSubmit
    @Log(title = "患者管理",businessType = BusinessType.INSERT)
    public AjaxResult add(HttpServletRequest request, @RequestBody @Valid PatientRequest params){

        params.setIdentityNumber(params.getIdentityNumber().toUpperCase());
        if(! IDCardValidator.isValid(params.getIdentityNumber())) {
            return AjaxResult.error("身份证号码不合法！");
        }

        if(StringUtils.isBlank(params.getDataType())) {
            params.setDataType(EquipmentConstants.EQUIPMENT_TYPE_MONITOR_PAD_TYPE);
        }

        // 如果用户是手填的患者数据，则需补充生日、性别、年龄数据
        if(params.getBirthday() == null || StringUtils.isBlank(params.getGender()) || params.getAge() == null ) {
            String identityNumber = params.getIdentityNumber();
            // 出生日期
            StringBuilder builder = new StringBuilder(identityNumber.substring(6, 14))
                    .insert(4, "-").insert(7, "-");
            String birthDayStr = builder.toString();
            params.setBirthday(DateUtils.dateTime(DateUtils.YYYY_MM_DD, birthDayStr));

            // 年龄
            int age = new Date().getYear() + 1900 - Integer.parseInt(birthDayStr.substring(0, 4));
            params.setAge(age);

            // 性别
            String sex = Sample.getSex("", identityNumber);
            params.setGender(sex);
        }

        appletTokenService.setUserDoctorAccountCache(request, params.getUserName());

        String doctorUser = visitService.add(params);
        return AjaxResult.success("患者登记成功！", doctorUser);
    }

    /**
     * 查询患者列表
     * @param dataType 数据类型
     * @return
     */
    @GetMapping("data")
    public AjaxResult list(String dataType){
        return AjaxResult.success(visitService.getList(dataType));
    }

    /**
     * 出院
     * @param visitNos 就诊号
     * @return
     */
    @RepeatSubmit
    @PostMapping("leaveHospital")
    public AjaxResult leaveHospital(@RequestBody @Size(min = 1, message = "患者就诊号不能为空！") List<Long> visitNos){
        return visitService.leaveHospital(visitNos);
    }

    /**
     * 根据身份证号码查询患者信息
     * @param idCardNo
     * @return
     */
    @GetMapping("searchByIdCardNo")
    public AjaxResult searchByIdCardNo(
            @NotBlank(message = "身份证号码不能为空！")
            @Pattern(regexp = RegConstants.ID_CARD, message = "身份证号格式有误！") String idCardNo) {

        idCardNo = idCardNo.toUpperCase();
        if(! IDCardValidator.isValid(idCardNo)) {
            return AjaxResult.error("身份证号码不合法！");
        }

        return AjaxResult.success(patIndexService.selectPatById(idCardNo));

    }
}
